package cn.leedsoft.luma.common.utils;

import cn.leedsoft.luma.plugins.spring.SpringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * Created by leeds on 2016/6/23 16:51.
 */
public class MessageUtil {
    private static final Logger logger = LoggerFactory.getLogger(MessageUtil.class);
    public static String getMessage(String key, Locale locale, String... args) {
        Assert.notNull(key, "message key can't be null!");
        if (locale == null) {
            locale = Locale.CHINESE;
        }
        MessageSource messageSource = SpringHelper.getBean(MessageSource.class);
        String message = null;
        try {
            message = messageSource.getMessage(key, args, locale);
        } catch (NoSuchMessageException e) {
            logger.error(String.format("i18n 读取message出错：message [%s] 不存在！", key));
            throw new RuntimeException(e);
        }
        return message;
    }
    public static String getMessage(String key, String... args) {
        Locale locale;
        try {
            HttpServletRequest request = RequestUtil.getRequest();
            locale = request.getLocale();
        } catch (IllegalArgumentException e) {
            logger.warn("can't get locale from request!");
            locale = null;
        }
        return getMessage(key, locale, args);
    }

    private static void varLengeth(String... args) {//可变参数个数，可以从0到n。如果是0个时候，args不是null，而是length为0的数组。
        System.out.println(args.length);
        if (args != null) {
            System.out.println("here");
            for (String arg : args) {
                System.out.println(arg);
            }
        } else
            System.out.println("args is null");
    }

    public static void main(String[] args) {
        System.out.println(getMessage("msg.test.a", "liziz"));
        System.out.println(getMessage("msg.test.b", "liziz"));
        System.out.println(getMessage("msg.test.a", Locale.ENGLISH,"liziz"));
        System.out.println(getMessage("msg.test.b", Locale.ENGLISH,"liziz"));
    }
}
